package com.li.net.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Server {
	public static final int SERVER_PORT = 12345;
	private static AsynchronousServerSocketChannel server;
	public Server() {
		// TODO Auto-generated constructor stub
	}

	public void start(){
		try {
			server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.1",SERVER_PORT));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		System.out.println("服务端启动.....");
		server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
			final ByteBuffer buffer = ByteBuffer.allocate(1024);
			@Override
			public void completed(AsynchronousSocketChannel result, Object attachment) {
				// TODO Auto-generated method stub
				System.out.println(Thread.currentThread().getName());
				Future<Integer> writeResult = null;
				try {
					buffer.clear();
					result.read(buffer).get(100, TimeUnit.SECONDS);
					System.out.println("In server: "+ new String(buffer.array()));
					buffer.flip();
					writeResult = result.write(buffer);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ExecutionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (TimeoutException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					server.accept(null,this);  
					try {  
						writeResult.get();  
						result.close();  
					} catch (InterruptedException | ExecutionException e) {  
						e.printStackTrace();  
					} catch (IOException e) {  
						e.printStackTrace();  
					}  
				}  

			}

			@Override
			public void failed(Throwable exc, Object attachment) {
				// TODO Auto-generated method stub

			}
		});
	}
	public static void main(String[] args) {
		new Server().start();
		while(true){  
            try {  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
	}
}
